package cn.wei.youvierpc.bootstrap;

import cn.wei.youvierpc.RpcApplication;
import cn.wei.youvierpc.config.RegistryConfig;
import cn.wei.youvierpc.config.RpcConfig;
import cn.wei.youvierpc.model.ServiceMetaInfo;
import cn.wei.youvierpc.model.ServiceRegisterInfo;
import cn.wei.youvierpc.registry.LocalRegistry;
import cn.wei.youvierpc.registry.Registry;
import cn.wei.youvierpc.registry.RegistryFactory;
import cn.wei.youvierpc.server.tcp.VertxTcpServer;

import java.util.List;

public class ProviderBootstrap {

    public static void init(List<ServiceRegisterInfo<?>> serviceRegisterInfos) {
        RpcApplication.init();
        final RpcConfig rpcConfig = RpcApplication.getRpcConfig();
        for (ServiceRegisterInfo<?> serviceRegisterInfo : serviceRegisterInfos) {
            String serviceName = serviceRegisterInfo.getServiceName();
            LocalRegistry.register(serviceName, serviceRegisterInfo.getImplClass());

            RegistryConfig registryConfig = rpcConfig.getRegistryConfig();
            Registry re = RegistryFactory.getInstance(registryConfig.getRegistry());

            ServiceMetaInfo serviceMetaInfo = new ServiceMetaInfo();
            serviceMetaInfo.setServiceName(serviceName);
            serviceMetaInfo.setServiceHost(rpcConfig.getServerHost());
            serviceMetaInfo.setServicePort(rpcConfig.getServerPort());

            try {
                re.register(serviceMetaInfo);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

        VertxTcpServer vertxTcpServer = new VertxTcpServer();
        vertxTcpServer.doStart(RpcApplication.getRpcConfig().getServerPort());
    }
}
